# Copyright 2018- The Pixie Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0

load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar")
load("@io_bazel_rules_docker//container:container.bzl", "container_bundle")
load("@io_bazel_rules_docker//contrib:push-all.bzl", "container_push")
load("//bazel:images.bzl", "image_map_with_bundle_version")

package(default_visibility = ["//visibility:public"])

OPERATOR_IMAGE_MAP = {
    "gcr.io/pixie-oss/pixie-dev/operator/operator_image": "//src/operator:operator_image",
    "gcr.io/pixie-oss/pixie-dev/operator/vizier_deleter": "//src/utils/pixie_deleter:vizier_deleter_image",
}

public_image_replacement = {"gcr.io/pixie-oss/pixie-dev": "gcr.io/pixie-oss/pixie-prod"}

config_setting(
    name = "public",
    values = {"define": "public=True"},
)

container_bundle(
    name = "private_operator_images_bundle",
    images = image_map_with_bundle_version(
        image_map = OPERATOR_IMAGE_MAP,
        replace = {},
        tag_latest = False,
    ),
)

container_bundle(
    name = "public_operator_images_bundle",
    images = image_map_with_bundle_version(
        image_map = OPERATOR_IMAGE_MAP,
        replace = public_image_replacement,
        tag_latest = False,
    ),
)

container_push(
    name = "operator_images_push",
    bundle = select({
        ":public": ":public_operator_images_bundle",
        "//conditions:default": ":private_operator_images_bundle",
    }),
    format = "Docker",
)

genrule(
    name = "vizier_crd_yaml",
    srcs = glob(["**/*.yaml"]),
    outs = ["vizier_crd.yaml"],
    cmd = """
      T=`mktemp -d`
      cp -aL k8s/operator/crd/base $$T
      kustomize build $$T/base -o $@
    """,
)

pkg_tar(
    name = "operator_templates",
    srcs = glob(
        [
            "helm/templates/*_*.yaml",
        ],
    ) + [
        "helm/crds",
        ":vizier_crd_yaml",
    ],
    package_dir = "/yamls",
    remap_paths = {
        "/operator/helm": "/",
        "/operator/vizier_crd.yaml": "/crds/vizier_crd.yaml",
    },
    strip_prefix = "/k8s",
)
